import Vue from 'vue'
import axios from 'axios'
var constants = require('./constants.js')
const timeout = 6000
let baseURL = constants.baseURL
const service = axios.create({
	withCredentials: true,
	crossDomain: true,
	baseURL,
	timeout
})


// 请求拦截器，可以定制请求头等
service.interceptors.request.use(config => {
		let token = uni.getStorageSync('token')
		if (token) {
			config.headers['token'] = token
		}
		if (config.method.toUpperCase() === 'POST' && config.headers['Content-Type'] == undefined) {
			config.headers['Content-Type'] = 'application/json;charset=UTF-8'
		}
		return config
	},
	error => {
		console.log(error)
		return Promise.reject(error)
	})

// 响应拦截器
service.interceptors.response.use(res => {
		if (res.status === 200) {
			return res
		}
		return res
	},
	error => {
		return Promise.reject(error)
	})


// 自己定义个适配器，用来适配uniapp的语法
axios.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				}
				settle(resolve, reject, response);
			}
		})
	})
}
export default service
